package com.fram.service.api.v1.android.impl;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fram.bean.admin.android.order.request.OrderAndroidRequest;
import com.fram.bean.admin.android.order.request.OrderDeliveredAndroidRequest;
import com.fram.bean.admin.android.order.request.ReportFormRequest;
import com.fram.bean.admin.android.order.response.OrderAndroidResponse;
import com.fram.bean.admin.android.order.response.OrderDetailAndroidResponse;
import com.fram.bean.admin.android.order.response.ReportFormResponse;
import com.fram.bean.admin.android.order.response.SalesVolumeResponse;
import com.fram.bean.admin.ordermain.response.PageAdminReportForm;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.ErrCode;
import com.fram.common.enums.OrderStatusEnum;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.base.BaseService;
import com.fram.common.util.date.DateUtils;
import com.fram.common.util.json.JSONTools;
import com.fram.entity.OrderMain;
import com.fram.mapper.OrderMainMapper;
import com.fram.service.api.v1.android.OrderAndroidService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class OrderAndroidServiceImpl extends BaseService implements OrderAndroidService{
	
	@Autowired
	private OrderMainMapper orderMainMapper;
	
	@Override
	public SalesVolumeResponse salesVolume(Long distributorId)throws ProException {
		SalesVolumeResponse salesVolumeResponse=orderMainMapper.salesVolume(distributorId);
		if(salesVolumeResponse == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return salesVolumeResponse;
	}
	
	@Override
	public PageInfo<OrderAndroidResponse> list(PageBean<OrderAndroidRequest> request) throws ProException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		if (!StringUtils.isEmpty(request.getParam().getCreateStartTime())) {
			request.getParam().setCreateStartTime(request.getParam().getCreateStartTime() + " 00:00:00");
		}
		if (!StringUtils.isEmpty(request.getParam().getCreateEndTime())) {
			try {
				request.getParam().setCreateEndTime(DateUtils.DF_SEPARATE.get()
						.format(DateUtils.getAddorSubtractTimes(DateUtils.DF_SEPARATE_YMD.get().parse(request.getParam().getCreateEndTime()), 0, 0, 0, 1, 0, 0)));
			} catch (ParseException e) {
			}
		}
		List<OrderAndroidResponse> list = orderMainMapper.listForAndroid(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		for (OrderAndroidResponse r : list) {
			r.setOrderStatusValue(OrderStatusEnum.orderStatusVaule(r.getOrderStatus()));
			r.setRefundStatusValue(OrderStatusEnum.orderStatusVaule(r.getRefundStatus()));
		}
		return new PageInfo<>(list);
	}

	@Override
	public OrderDetailAndroidResponse detail(Long id) throws ProException {
		OrderDetailAndroidResponse detail=orderMainMapper.androidOrderDetail(id);
		if(detail == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		detail.setOrderStatusValue(OrderStatusEnum.orderStatusVaule(detail.getOrderStatus()));
		if (detail.getRefundOrder() != null) {
			detail.setRefundStatusValue(OrderStatusEnum.orderStatusVaule(detail.getRefundOrder().getRefundStatus()));
		}
		return detail;
	}

	@Override
	public void orderDelivered(OrderDeliveredAndroidRequest request) throws ProException {
		if (!StringUtils.isEmpty(request.getRemark()) && request.getRemark().length() > 256) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "备注字数不能超过256个字");
		}
		OrderMain order = orderMainMapper.selectByPrimaryKey(request.getId());
		if (order == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (request.getDistributorId() != null && request.getDistributorId() != order.getDistributorId()) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "该订单无权操作");
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus() != order.getOrderStatus()) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "该订单不是已支付，不能发货");
		}
		OrderMain update = new OrderMain();
		update.setId(request.getId());
		update.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus());
		update.setDeliveryTime(new Date());
		update.setRemark(request.getRemark());
		int i = orderMainMapper.updateByPrimaryKeySelective(update);
		if (i <= 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "发货失败");
		}
	}

	@Override
	@Transactional
	public PageAdminReportForm reportForm(Long distributorId) throws ProAffairException {
		String key = "ADMIN_PAGE_REPORT_FORM_" + distributorId;
		int db = 15;
		Object data = redisService.get(db, key);
		if (!StringUtils.isEmpty(data)) {
			return JSONTools.jsonStr2obj(data.toString(), PageAdminReportForm.class);
		}
		PageAdminReportForm form = new PageAdminReportForm();
		Date date = new Date();
		// 今日
		String today = DateUtils.DF_SEPARATE_YMD.get().format(date);
		form.setTodayData(orderMainMapper.orderStatusByDay(today + " 00:00:00", today + " 23:59:59", distributorId));
		// 昨日
		String yesterDay = DateUtils.DF_SEPARATE_YMD.get().format(DateUtils.getAddorSubtractTimes(date, 0, 0, 0, -1, 0, 0));
		form.setYesterdayData(orderMainMapper.orderStatusByDay(yesterDay + " 00:00:00", yesterDay + " 23:59:59", distributorId));
		// 七天之内
		String seven = DateUtils.DF_SEPARATE_YMD.get().format(DateUtils.getAddorSubtractTimes(date, 0, 0, 0, -6, 0, 0));
		form.setSevenDayData(orderMainMapper.orderStatusByDay(seven + " 00:00:00", today + " 23:59:59", distributorId));
		// 这周
		String thisWeek = DateUtils.DF_SEPARATE_YMD.get().format(DateUtils.getAddorSubtractTimes(date, 0, 0, 0, (DateUtils.getWeekByDay(date) - 1) * -1, 0, 0));
		form.setThisWeekData(orderMainMapper.orderStatusByDay(thisWeek + " 00:00:00", today + " 23:59:59", distributorId));
		// 30天
		String thirty = DateUtils.DF_SEPARATE_YMD.get().format(DateUtils.getAddorSubtractTimes(date, 0, 0, 0, -29, 0, 0));
		form.setThirtyDayData(orderMainMapper.orderStatusByDay(thirty + " 00:00:00", today + " 23:59:59", distributorId));
		// 这个月
		String thisMonth = today.substring(0, 8) + "01";
		form.setThisMonthData(orderMainMapper.orderStatusByDay(thisMonth + " 00:00:00", today + " 23:59:59", distributorId));

		// 存入redis 整点30分更新一次
		int expireTime = 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		int minute = calendar.get(Calendar.MINUTE);
		if (minute > 30) {
			expireTime = 60 - minute;
		} else {
			expireTime = 30 - minute;
		}
		redisService.set(db, key, JSONTools.obj2json(form), expireTime * 60);
		return form;
	}

	@Override
	public List<ReportFormResponse> reportForm(ReportFormRequest request)throws ProException{
		List<ReportFormResponse> list= orderMainMapper.reportForm(request);
		if(list == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}
}
